﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenNetCommerce.Localization.resources;

namespace OpenNetCommerce.Localization
{
	public class LocalizeAttribute : Attribute
	{
		private string _labelKey
			, _helpKey;

		public LocalizeAttribute()
		{
		}

		public LocalizeAttribute(string labelKey, string helpKey)
		{
			_labelKey = labelKey;
			_helpKey = helpKey;
		}

		public static string GetHelpText<T>(string propertyName)
		{
			return GetHelpText(typeof (T), propertyName);
		}

		public static string GetHelpText(object instance, string propertyName)
		{
			return GetHelpText(instance.GetType(), propertyName);
		}

		public static string GetHelpText(Type type, string propertyName)
		{
			var pi = type.GetProperty(propertyName);
			if (pi == null)
				return null;
			var la = LocalizeAttribute.GetCustomAttribute(pi, typeof (LocalizeAttribute)) as LocalizeAttribute;
			if (la == null)
				return null;
			return help.ResourceManager.GetString(la._helpKey ?? ("help" + GetDefaultResxKey(type, propertyName))) ?? String.Empty;
		}

		public static string GetLabelText<T>(string propertyName)
		{
			return GetLabelText(typeof(T), propertyName);
		}

		public static string GetLabelText(object instance, string propertyName)
		{
			return GetLabelText(instance.GetType(), propertyName);
		}

		public static string GetLabelText(Type type, string propertyName)
		{
			var pi = type.GetProperty(propertyName);
			if (pi == null)
				return null;
			var la = LocalizeAttribute.GetCustomAttribute(pi, typeof (LocalizeAttribute)) as LocalizeAttribute;
			if (la == null)
				return null;
			return labels.ResourceManager.GetString(la._labelKey ?? ("lbl" + GetDefaultResxKey(type, propertyName))) ?? String.Empty;
		}

		private static string GetDefaultResxKey(Type type, string propertyName)
		{
			return type.Name + "_" + propertyName;
		}
	}
}
